package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.biz.enums.EarMarkType;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.model.EarMarkLife;
import com.dongjiantong.biz.model.EarMarks;
import com.dongjiantong.biz.service.EarMarkLifeWriteService;
import com.dongjiantong.biz.service.EarMarksWriteService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.farmrecords.dto.CowRecordDto;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.enums.ProductRelateTypeEnum;
import com.dongjiantong.farmrecords.mapper.FarmRecordsBullRecordsMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsCowRecords;
import com.dongjiantong.farmrecords.model.FarmRecordsProduction;
import com.dongjiantong.farmrecords.service.*;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.sys.enums.AnimalTypeEnum;
import com.dongjiantong.sys.enums.DicUnitEnum;
import com.dongjiantong.user.enums.FarmsEnum;
import com.dongjiantong.user.service.FarmsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 牛档案
 * @author Lee
 * @date 2018/1/9
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsCowRecordsServiceImpl extends ServiceMybatis<FarmRecordsCowRecords> implements FarmRecordsCowRecordsService {
    @Resource
    private FarmRecordsBullRecordsMapper farmRecordsBullRecordsMapper;

    @Resource
    private FarmRecordsProductionService farmRecordsProductionService;
    @Resource
    private FarmRecordsImmunizationService farmRecordsImmunizationService;
    @Resource
    private FarmRecordsDiagnosisService farmRecordsDiagnosisService;
    @Resource
    private FarmRecordsHarmlessesService farmRecordsHarmlessesService;

    @Reference(version = "1.0.0")
    private EarMarksWriteService earMarksWriteService;
    @Reference(version = "1.0.0",retries = 0,timeout = 6000)
    private EarMarkLifeWriteService earMarkLifeWriteService;
    @Reference(version = "1.0.0")
    private FarmsService farmsService;

    /**
     * 养殖端按状态分页查看牛档案
     * @param pageNum
     * @param pageSize
     * @param status
     * @param farmId
     * @param cowNumber
     * @return
     */
    @Override
    public PageInfo<CowRecordDto> selectListByStatus(Integer pageNum, Integer pageSize, List<Integer> status, Long farmId, String cowNumber) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status.size() > 0) {
            map.put("statusList",status);
        }
        map.put("farm_id",farmId);

        if (!Strings.isNullOrEmpty(cowNumber)) {
            map.put("cow_number",cowNumber);
        }

        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

        List<FarmRecordsCowRecords> farmRecordsCowRecordsList = farmRecordsBullRecordsMapper.selectListByStatus(map);

        //todo
        List<CowRecordDto> cowRecordDtoList = this.setCowRecordsDto(farmRecordsCowRecordsList);

        return new PageInfo<CowRecordDto>(cowRecordDtoList);
    }

    //设置返回cowRecordDto包装类
    @Override
    public List<CowRecordDto> setCowRecordsDto(List<FarmRecordsCowRecords> farmRecordsCowRecordsList) {
        List<CowRecordDto> list = Lists.newArrayList();
        List<Long> ids = Lists.newArrayList();
        if (farmRecordsCowRecordsList.size()  > 0) {
            for (FarmRecordsCowRecords farmRecordsBullRecords : farmRecordsCowRecordsList) {
                ids.add(farmRecordsBullRecords.getId());
            }
        }

        if (ids.size() > 0) {
            //根据牛档案关联单据ids 查询诊疗次数
            List<Map<String,Object>> diagnosisCount = farmRecordsDiagnosisService.selectDiagnosisCount(ids);
            //根据牛档案关联单据Ids 查询免疫次数
            List<Map<String,Object>> immunizationCount = farmRecordsImmunizationService.selectImmunizationCount(ids);
            //根据牛档案关联单据ids 查询无害化
            List<Map<String,Object>> harmlessesCount = farmRecordsHarmlessesService.selectHarmlessesNoCenterCount(ids);

            Map<Long,Object> diagnosisMap =Maps.newHashMap();
            for (Map<String,Object> diagnosis : diagnosisCount) {
                Long id = (Long) diagnosis.get("id");
                diagnosisMap.put(id,diagnosis.get("count"));
            }
            Map<Long,Object> immunizationMap = Maps.newHashMap();
            for (Map<String,Object> immunization : immunizationCount) {
                Long id = (Long) immunization.get("id");
                immunizationMap.put(id,immunization.get("count"));
            }
            Map<Long,Object> harmlessesMap = Maps.newHashMap();
            for (Map<String,Object> harmlesses : harmlessesCount) {
                Long id = (Long) harmlesses.get("id");
                harmlessesMap.put(id,harmlesses.get("count"));
            }


            for (FarmRecordsCowRecords farmRecordsBullRecords : farmRecordsCowRecordsList) {
                Integer diagnosisResult = (Integer) diagnosisMap.get(farmRecordsBullRecords.getId());
                Integer immunizationResult = (Integer) immunizationMap.get(farmRecordsBullRecords.getId());
                Integer harmlessesResult = (Integer) harmlessesMap.get(farmRecordsBullRecords.getId());

                CowRecordDto cowRecordDto = new CowRecordDto();
                cowRecordDto.setCowRecord(farmRecordsBullRecords);
                cowRecordDto.setDiagnosisCount(diagnosisResult == null ? 0 : diagnosisResult);
                cowRecordDto.setImmunizationCount(immunizationResult == null ? 0 : immunizationResult);
                cowRecordDto.setIsHarmlesses(harmlessesResult == null ? false : true);
                list.add(cowRecordDto);
            }
        }

        return list;
    }

    /**
     * 政府端分页查看牛档案
     * @param pageNum
     * @param pageSize
     * @param map
     * @return
     */
    @Override
    public PageInfo<FarmRecordsCowRecords> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsBullRecordsMapper == null){
                throw new OPServerException("farmRecordsBullRecordsMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsCowRecords> farmRecordsCowRecordsList = farmRecordsBullRecordsMapper.selectByMap(map);

            return new PageInfo<FarmRecordsCowRecords>(farmRecordsCowRecordsList);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 更新牛档案
     * @param farmRecordsBullRecords
     * @param toStatus
     * @return
     */
    @Override
    public Integer updateByIdOrNumber(FarmRecordsCowRecords farmRecordsBullRecords, Integer toStatus) {
        if (farmRecordsBullRecordsMapper == null) { throw new OPServerException("farmRecordsBullRecordsMapper 服务为空,请重启服务后重试"); }

        farmRecordsBullRecords.setStatus(toStatus);
        farmRecordsBullRecords.setUpdated_at(new Date());

        int con = farmRecordsBullRecordsMapper.updateByPrimaryKeySelective(farmRecordsBullRecords);

        return con;
    }

    @Override
    public Integer deleteById() {
        return null;
    }

    /**
     * 更新牛档案耳标
     * @param earTagNumber
     * @return
     */
    @Override
    public Boolean updateEarNumber(String earTagNumber,String beforeEarTogNumber) {

        boolean result = false;
        int before = 0;
        int after = 0;

        //更新原有耳标状态
        if (!Strings.isNullOrEmpty(beforeEarTogNumber)) {
            EarMarks earMarks = new EarMarks();
            earMarks.setMark_number(beforeEarTogNumber);
            earMarks.setStatus(EarMarkType.status_put.getCode());
            earMarks.setCreated_at(new Date());
            earMarksWriteService.updateByPrimaryKeySelective(earMarks);
        }
        if (!Strings.isNullOrEmpty(earTagNumber)) {
            //更新当前耳标状态
            EarMarks earMarks = new EarMarks();
            earMarks.setMark_number(earTagNumber);
            earMarks.setStatus(EarMarkType.status_wear.getCode());
            earMarks.setWore_at(new Date());
            after = earMarksWriteService.updateByPrimaryKeySelective(earMarks);
        }

        if (after != 0) {
            result = true;
        }

        return result;
    }

    /**
     * 新建牛档案
     * @param farmRecordsBullRecords
     * @param toStatus
     * @return
     */
    @Override
    public Map<String, Object> createOne(LoginInfo loginInfo, FarmRecordsCowRecords farmRecordsBullRecords, Integer toStatus) {
        Map<String,Object> result = Maps.newHashMap();

        if (farmRecordsBullRecordsMapper == null) {
            throw new OPServerException("farmRecordsBullRecordsMapper服务未注册");
        }

        Integer fromStatus = farmRecordsBullRecords.getStatus();

        //生成单据号
        String prefix = "ND";
        prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
        String maxNumber = farmRecordsBullRecordsMapper.findMaxNumber(prefix);
        String number = ReportNumberMakerUtil.create(prefix,maxNumber);
        farmRecordsBullRecords.setNumber(number);

        farmRecordsBullRecords.setIs_selected(1);
        farmRecordsBullRecords.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

        if (fromStatus == 0 && toStatus == null) {
            farmRecordsBullRecordsMapper.createOne(farmRecordsBullRecords);
        } else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)) {
            farmRecordsBullRecords.setStatus(toStatus);
            //直接提交单据
            farmRecordsBullRecordsMapper.createOne(farmRecordsBullRecords);

            if (farmRecordsBullRecords.getId() != null) {
                //todo 生成生产记录单据
                FarmRecordsProduction farmRecordsProduction = this.createFarmrecordsProduction(loginInfo,farmRecordsBullRecords);

                farmRecordsProductionService.createOne(loginInfo,farmRecordsProduction,FarmRecordsNumberStatus.SUBMIT.getCode(),2);

                //todo 更新耳标状态
                String earTogNumber = farmRecordsBullRecords.getEar_tag_number();

                if(!Strings.isNullOrEmpty(earTogNumber)) {
                    Map<String,Object> earParam = Maps.newHashMap();
                    earParam.put("markNumber",earTogNumber);
                    earParam.put("status", EarMarkType.status_wear.getCode());
                    earParam.put("woreAt",new Date());

                    earMarksWriteService.updateMarks(earParam);

                    //新增耳标的使用记录
                    EarMarkLife earMarkLife = new EarMarkLife();
                    earMarkLife.setMark_number(earTogNumber);
                    earMarkLife.setMark_type(farmRecordsBullRecords.getBreed_second_type());
                    earMarkLife.setReport_id(farmRecordsBullRecords.getId());
                    earMarkLife.setReport_name(farmRecordsBullRecords.getNumber());
                    earMarkLife.setReport_type(ReportType.IMMUNIZATION_RECORD_MANAGER.value());
                    earMarkLife.setIs_selected(1);
                    earMarkLife.setOperator_id(loginInfo.getId());
                    earMarkLife.setOperator_name(loginInfo.getRealName());
                    earMarkLife.setCreated_at(new Date());

                    earMarkLifeWriteService.insert(earMarkLife);
                }
            }
        }

        if (farmRecordsBullRecords.getId() != null) {
            result.put("receiptId",farmRecordsBullRecords.getId());
        }
        if (!Strings.isNullOrEmpty(farmRecordsBullRecords.getEar_tag_number())) {
            result.put("earTogNumber",farmRecordsBullRecords.getEar_tag_number());
        }
        if (!Strings.isNullOrEmpty(farmRecordsBullRecords.getCow_number())) {
            result.put("cowNumber",farmRecordsBullRecords.getEar_tag_number());
        }

        return result;
    }

    /**
     * 新建牛档案的时候新增一单生产记录
     * @param loginInfo
     * @param farmRecordsBullRecords
     * @return
     */
    private FarmRecordsProduction createFarmrecordsProduction(LoginInfo loginInfo,FarmRecordsCowRecords farmRecordsBullRecords) {
        FarmRecordsProduction farmRecordsProduction = new FarmRecordsProduction();

        farmRecordsProduction.setRelate_type(ProductRelateTypeEnum.BULL_RECORDS.getCode());
        farmRecordsProduction.setRelate_id(farmRecordsBullRecords.getId());
        farmRecordsProduction.setRelate_number(farmRecordsBullRecords.getNumber());
        farmRecordsProduction.setCow_number(farmRecordsBullRecords.getCow_number());

        farmRecordsProduction.setStatus(FarmRecordsNumberStatus.TEMPORARY.getCode());
        farmRecordsProduction.setFarm_id(farmRecordsBullRecords.getFarm_id());
        farmRecordsProduction.setFarm_name(farmRecordsBullRecords.getFarm_name());
        farmRecordsProduction.setCow_number(farmRecordsBullRecords.getCow_number());

        farmRecordsProduction.setDate(new Date());

        if (farmRecordsBullRecords.getStable_id() != null) {
            farmRecordsProduction.setStable_id(farmRecordsBullRecords.getStable_id());
            farmRecordsProduction.setStable_number(farmRecordsBullRecords.getStable_number());
        }

        farmRecordsProduction.setBreed_type(AnimalTypeEnum.LIVESTOCK.getCode());
        farmRecordsProduction.setBreed_second_type(farmRecordsBullRecords.getBreed_second_type());
        farmRecordsProduction.setBreed_third_type(farmRecordsBullRecords.getBreed_third_type());

        farmRecordsProduction.setUnit(DicUnitEnum.SYS_UNIT_HEAD.getCode());
        //牛一次一头
        farmRecordsProduction.setChange_quantity(1);
        farmRecordsProduction.setBirth_quantity(1);

        farmRecordsProduction.setIn_quantity(0);
        farmRecordsProduction.setOut_quantity(0);
        farmRecordsProduction.setDeath_quantity(0);

        return farmRecordsProduction;
    }
}
